package admin

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"iris_blog/utils"
	"strings"
)

type Article struct {
	Max int
}

func (a Article) GetArticleList(i iris.Context) {

	results := []map[string]interface{}{}
	utils.DB.Raw("SELECT A.id, A.title, A.content, A.add_time, A.img, A.nav_id, A.content_html,  group_concat(tag_id) FROM article AS A LEFT JOIN tag_article ON A.id = tag_article.article_id LEFT JOIN tag ON tag.id = tag_article.tag_id GROUP BY A.id").Find(&results)

	for r := range results {
		s, _ := results[r]["group_concat(tag_id)"].(string)

		strArr := strings.Split(s,",")

		res := []map[string]interface{}{}
		utils.DB.Debug().Raw("SELECT * FROM tag WHERE id IN (?)", strArr).Find(&res)
		fmt.Println(res)

		//results[r]["group_concat(tag_id)"] = res
		results[r]["tag"] = res
		results[r]["tag_res_id"] = strArr
		delete(results[r],"group_concat(tag_id)")
		//i2,_ := results[r]["group_concat(tag_id)"].(string)
		//fmt.Println(i2)
	}

	i.JSON(map[string]interface{}{
		"code": 20000,
		"data": results,
	})
}

/**
添加文章
*/
func (a Article) AddArticle(i iris.Context) {
	result := map[string]interface{}{}
	i.ReadJSON(&result)
	fmt.Println(result)
	results := map[string]interface{}{}
	utils.DB.Raw("INSERT INTO article "+
		"(title, content, add_time, img, nav_id, content_html) VALUES (?,?,?,?,?,?)",
		result["title"], result["content"], utils.GetUnix(), result["img"], result["nav"], result["content_html"]).Find(&results)


	fmt.Println(result["tag"])
	val, ok := result["tag"].([]interface{})
	if ok {
		fmt.Println("转换错误", ok)
	}
	fmt.Println(val, "'----------'s")

	res := map[string]interface{}{}
	utils.DB.Raw("SELECT LAST_INSERT_ID()").Find(&res)
	fmt.Println(res)

	for _,value := range val {
		fmt.Println(value,"======")
		r := map[string]interface{}{}
		utils.DB.Raw("INSERT INTO tag_article (tag_id, article_id) VALUES (?,?)", value, res["LAST_INSERT_ID()"]).Find(&r)
	}

	fmt.Println(res)

	i.JSON(map[string]interface{}{
		"code": 20000,
		"data": res,
	})
}

/**
删除文章
*/

func (a Article) DelArticle(i iris.Context) {
	result := map[string]interface{}{}
	i.ReadJSON(&result)

	fmt.Println(result)

	results := map[string]interface{}{}
	err := utils.DB.Raw("DELETE FROM article WHERE id = ?", result["id"]).Find(&results).Error

	if err != nil {
		i.JSON(map[string]interface{}{
			"code": 20001,
			"msg":  "删除失败",
			"data": results,
		})
	}

	i.JSON(map[string]interface{}{
		"code": 20000,
		"msg":  "删除成功",
		"data": results,
	})
}
